package com.xcc.util;

import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.sun.xml.internal.ws.policy.privateutil.PolicyUtils;
import com.xcc.exception.ParamException;
import org.apache.commons.collections.MapUtils;

import javax.validation.*;
import java.util.*;

/**
 * @outhor Ren
 * @create 2019-03-20 22:23
 * 描述:
 * 类参数校验器
 */
public class BeanValidator {

    /**
     * 校验主类
     */
    private final static ValidatorFactory VALIDATOR_FACTORY = Validation.buildDefaultValidatorFactory();


    /**
     * 对象校验
     *
     * @param t
     * @param groups
     * @param <T>
     * @return
     */
    public static <T> Map<String, String> validate(T t, Class<T>... groups) {
        Validator validator = VALIDATOR_FACTORY.getValidator();
        Set validateResult = validator.validate(t, groups);
        // 是否有错误信息
        if (validateResult.isEmpty()) {
            return Collections.emptyMap();
        } else {
            LinkedHashMap errors = Maps.newLinkedHashMap();
            // 获取错误信息
            Iterator iterator = validateResult.iterator();
            while (iterator.hasNext()) {
                ConstraintViolation violation = (ConstraintViolation) iterator.next();
                // 添加相关信息
                errors.put(violation.getPropertyPath().toString(),
                        violation.getMessage());
            }
            return errors;
        }
    }

    /**
     * 校验 list
     *
     * @param collection
     * @return
     */
    public static Map<String, String> validateList(Collection<?> collection) {
        // 判断是否为空
        Preconditions.checkNotNull(collection);

        // 获取 list 对象
        Iterator iterator = collection.iterator();
        Map errors;
        do {
            if (!iterator.hasNext()) {
                return Collections.emptyMap();
            }
            Object object = iterator.next();
            // 校验该类
            errors = validate(object, new Class[0]);
        } while (errors.isEmpty());
        return errors;
    }

    /**
     * 对象校验
     *
     * @param first
     * @param objects
     * @return
     */
    public static Map<String, String> validateObject(Object first, Object... objects) {
        if (objects != null && objects.length > 0) {
            return validateList(Lists.asList(first, objects));
        }
        return validate(first, new Class[0]);
    }

    /**
     * 参数校验
     *
     * @param params
     * @throws ParamException
     */
    public static void check(Object params) throws ParamException {
        Map<String, String> map = BeanValidator.validateObject(params);
        if (MapUtils.isNotEmpty(map)) {
            throw new ParamException(map.toString());
        }
    }

}
